package com.tulele.vtool.task.async;


import com.tulele.vtool.model.PlatformSysInfo;
import com.tulele.vtool.model.SysGzh;
import com.tulele.vtool.model.UserInfo;
import com.tulele.vtool.service.IUserInfoService;
import com.tulele.vtool.service.SysGzhService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ArticleTableInfoTask {
    @Autowired
    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private SysGzhService sysGzhService;

    /**
     * 填写文章表单发送模板消息
     * @param userId 提交表单的用户 ID
     * @param articleUserId 文章所有者 ID
     * @param gzhCode 公众号标识
     */
    @Async
    public void sendArticleTableMsg(Integer userId, Integer articleUserId, String gzhCode) {
        WeixinServiceDL weixinService = WeixinServiceMap.getWeixinService(gzhCode);
        if (weixinService == null) {
            weixinService = objectFactory.getObject();
            weixinService.reSetConfigStorage(gzhCode);
            WeixinServiceMap.putWeixinService(gzhCode, weixinService);
        }

        PlatformSysInfo platformSysInfoConfig = sysGzhService.getPlatformSysInfo(gzhCode);

        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                // 接收者openid
                .toUser(userInfoService.getUserOpenId(articleUserId))
                // 模板id
                .templateId(platformSysInfoConfig.getSysGzh().getCustomerFollowupTempId())//客户跟进提醒
                // 模板跳转链接
                .url(platformSysInfoConfig.getFrontDomain() + "pages/Newpage/Formfeedback.html")// 表单反馈页
                .build();

        // 恭喜您收获意向客户新表单一份    客户姓名XXX，五星意向客户、回复数字【 X 】马上联系成交~
        String firstMsg = "恭喜您收获意向客户新表单一份";

        String remarkMsg = "\uD83D\uDC49回复数字【 1 】马上联系成交~";

        // 添加模板数据
        templateMessage.addData(new WxMpTemplateData("first", firstMsg, "#FF00FF"))
                .addData(new WxMpTemplateData("keyword1", "-", "#A9A9A9"))
                .addData(new WxMpTemplateData("keyword2", userInfoService.getUserInfo(userId).getNickName(), "#A9A9A9"))
                .addData(new WxMpTemplateData("keyword3", "五星意向客户", "#A9A9A9"))
                .addData(new WxMpTemplateData("remark", remarkMsg, "#FF0000"));

        try {
            weixinService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
    }
}
